use std::ops::Deref;

use crate::{JObject, JVm};

#[repr(transparent)]
pub struct JLocal<'a, T: AsRef<JObject> + 'static> {
	inner: &'a T,
}
impl<'a, T: AsRef<JObject> + 'static> Drop for JLocal<'a, T> {
	fn drop(&mut self) {
		JVm::singleton(None).unwrap().env().unwrap().del_local(self.inner.as_ref())
	}
}
impl<'a, T: AsRef<JObject> + 'static> JLocal<'a, T> {
	pub(crate) fn try_from(value: sys::jobject) -> Result<Self, ()> {
		if !value.is_null() {
			Ok(Self {
				inner: unsafe { &*(value as *mut T) },
			})
		} else {
			Err(())
		}
	}
}

impl<'a, T: AsRef<JObject> + 'static> Deref for JLocal<'a, T> {
	type Target = T;
	fn deref(&self) -> &Self::Target {
		self.inner
	}
}
